package com.gitee.zhangchenyan.takin.service.common;

import cn.hutool.core.convert.Convert;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AlibabaNacos implements InitializingBean, DisposableBean {

    @Value("${takin.nacosServerAddress}")
    private String nacosAddr;
    private NamingService namingService;//主要用作服务方面的管理功能

    //注册服务
    public void registerServer(String nacosServerName, String ip, int port) throws Exception {
        Instance instance = new Instance();
        instance.setServiceName(nacosServerName);
        instance.setIp(ip);
        instance.setPort(port);
        namingService.registerInstance(instance.getServiceName(), instance);
    }

    //删除服务
    public void deleteServer(String nacosServerName, String ip, int port) throws Exception {
        Instance instance = new Instance();
        instance.setServiceName(nacosServerName);
        instance.setIp(ip);
        instance.setPort(port);
        namingService.deregisterInstance(instance.getServiceName(), instance.getIp(), instance.getPort());
    }

    //随机全部（有可能获取到的不健康）。拿到全部实例后，我们可以按照自己的负载均衡算法进行调用。类似于springcloud的ribbon。
    public List<Instance> getAllServer(String nacosServerName) throws Exception {
        return namingService.getAllInstances(nacosServerName);
    }
    //根据负载均衡算法获取一个健康的实例
    public Instance getOneHealthyInstance(String nacosServerName) throws NacosException {
        return namingService.selectOneHealthyInstance(nacosServerName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        namingService = NacosFactory.createNamingService(this.nacosAddr);
    }

    @Override
    public void destroy() throws Exception {
        namingService.shutDown();
    }

    //更多api请参数：https://nacos.io/zh-cn/docs/open-api.html
}
